package com.hk.yajin.utills;

import android.text.TextUtils;
import android.util.Log;

import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.XUtillsDBManeger;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.Attach;
import com.hk.yajin.model.Message;

import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;

import java.util.List;

/**
 * 作者：wl on 2017/7/26 17:33
 * 邮箱：wangl@ixinyongjia.com
 */
public class MessageHelper {
    private DbManager db;
    private static MessageHelper instance;
    private static int userid;

    //接收构造方法初始化的DbManager对象
    public MessageHelper(int UserId) {
        db = new XUtillsDBManeger(UserId).getDb();
    }

    public static MessageHelper getInstance() {
        if (instance == null) {
            instance = new MessageHelper(UserInfoManager.getInstance().getUserInfo().getUser_id());
        }
        return instance;
    }

    /*登陆切换*/
    public static void restDataBaseId() {
        userid = UserInfoManager.getInstance().getUserInfo().getUser_id();
        instance = new MessageHelper(userid);
    }


    /****************************************************************************************/


    private void convertAtachToString(List<Message> msgs) {
        for (Message msg : msgs) {
            if (msg.getMail_attachs() != null && msg.getMail_attachs().size() > 0) {
                msg.setAttach_json(FastjsonUtils.toJSONString(msg.getMail_attachs()));
            }
            msg.setUser_id(UserInfoManager.getInstance().getUserInfo().getUser_id());
        }
    }

    private void convertStringToAtach(List<Message> msgs) {
        for (Message msg : msgs) {
            if (!TextUtils.isEmpty(msg.getAttach_json())) {
                msg.setMail_attachs(FastjsonUtils.getBeanList(msg.getAttach_json(), Attach.class));
            }
        }
    }

    public void saveMessages(final List<Message> msgs) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (msgs != null && msgs.size() > 0) {
                    convertAtachToString(msgs);
                    try {
                        db.saveOrUpdate(msgs);
                        LogUtil.d("消息存储成功");
                    } catch (DbException e) {
                        LogUtil.d("消息存储异常：" + e.getMessage());
                    }
                }
            }
        }).start();

    }


    /*获取指定时间之后的20条数据*/
    public List<Message> getOldMessageByMinId(int minId, int num) {
        List<Message> messageList = null;
        try {
            messageList = db.selector(Message.class).expr("log_id<" + minId).and("user_id", "=", UserInfoManager.getInstance().getUserInfo().getUser_id()).orderBy("log_id", true).limit(num).findAll();
            convertStringToAtach(messageList);
        } catch (DbException e) {
            e.printStackTrace();
        } finally {
            return messageList;
        }
    }

    public boolean hasMoreOldMessage(int minId) {
        long count = -1;
        try {
            count = db.selector(Message.class).expr("log_id<" + minId).and("user_id", "=", UserInfoManager.getInstance().getUserInfo().getUser_id()).orderBy("log_id", true).count();
            LogUtil.d("查询id小于" + minId + "的数量为：" + count);
            LogUtil.d("数据库路径："+db.getDatabase().getPath());

        } catch (DbException e) {
            e.printStackTrace();
        } finally {
            return count > 0 ? true : false;
        }
    }

    /*初始化获取num条数据*/
    public List<Message> getInitMessage(int num) {
        List<Message> messageList = null;
        try {
            messageList = db.selector(Message.class).orderBy("log_id", true).limit(num).findAll();
            convertStringToAtach(messageList);
            LogUtil.d("数据库路径："+db.getDaoConfig().getDbDir().getName());
        } catch (DbException e) {
            e.printStackTrace();
        } finally {
            return messageList;
        }
    }


}
